//
//  ToolMethods.m
//  KiWiPeniOSProject
//
//  Created by 曾威林 on 2017/8/18.
//  Copyright © 2017年 zjy. All rights reserved.
//

#import "ToolMethods.h"

@implementation ToolMethods

+ (NSString *)generateRandomNumbers {
    NSString *randomStr = @"";
    for (int i = 0; i < 8; i ++) {
        int num = arc4random()%10;
        randomStr = [randomStr stringByAppendingString:[NSString stringWithFormat:@"%ld",(long)num]];
    }
    return randomStr;
}

+ (long long)generateTimestamp {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    long long time = (long long)[datenow timeIntervalSince1970] * 1000;
    //NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970] * 1000)];
    return time;
}

+ (void)saveMobileTokenWithMobileToken:(NSString *)mobileToken {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:mobileToken forKey:@"mobileToken"];
    [userDefaults synchronize];
}

+ (void)saveAccessTokenWithAccessToken:(NSString *)accessToken {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:accessToken forKey:@"accessToken"];
    //保存一下
    [userDefaults synchronize];
}

+ (NSString *)getMobileToken {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *str = [userDefaults objectForKey:@"mobileToken"];
    return str;
}

+ (NSString *)getAccessToken {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *str = [userDefaults objectForKey:@"accessToken"];
    return str;
}


+ (void) deleteKiwipenInfoWithUUID:(NSString *) uuid {
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSMutableArray<NSDictionary *> *dictArray = [userDefault mutableArrayValueForKey:@"kiwipenInfoArray"];
    
    NSMutableArray *resultArray = [NSMutableArray array];
    
    for (NSDictionary *tempDict in dictArray) {
        if (![[tempDict objectForKey:@"uuid"] isEqualToString:uuid]) {
            [resultArray addObject:tempDict];
        }
    }
    
    
    [userDefault setObject:resultArray forKey:@"kiwipenInfoArray"];
    [userDefault synchronize];
    
}



+ (BOOL)judgeIfIsRightMobileNumberWithMobileNumber:(NSString *)mobileNumber {
    //手机号长度必须是11位
    NSInteger length = mobileNumber.length;
    if (length != 11) {
        return NO;
    }
    //第一位数必须是1
    NSString *firstNo = [mobileNumber substringToIndex:1];
    if (![firstNo isEqualToString:@"1"]) {
        return NO;
    }
    //第二位数不能是1，2，6，9
    NSString *firstTwoNo = [mobileNumber substringToIndex:2];
    NSString *secondNo = [firstTwoNo substringFromIndex:1];
    if ([secondNo isEqualToString:@"1"] || [secondNo isEqualToString:@"2"] || [secondNo isEqualToString:@"6"] || [secondNo isEqualToString:@"9"]) {
        return NO;
    }
    return YES;
}

//获取当前的导航控制器
+ (UINavigationController *) getRootNavigationController {
    
    //UIAlertView 或 UIActionSheet 在系统级使用了 presentModelViewController，并且修改了 Application 中更换了 keyWindow
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIViewController *rootVC = [window rootViewController];
    while (rootVC.presentedViewController) {
        rootVC = rootVC.presentedViewController;
    }
    
    return (UINavigationController*)rootVC;
}

//获取当前屏幕显示的viewcontroller
+ (UIViewController *) getCurrentVC
{
    UIViewController *result = [self getPresentedViewController];
    
    if ([result isKindOfClass:[UINavigationController class]]) {
        result = [result childViewControllers].lastObject;
    }
    
    return result;
}

//替换当前页面
+ (void) replaceCurrentVCWithVC:(UIViewController *) newVC {
    
    // Replace the current view controller
    NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:[[self getRootNavigationController] viewControllers]];
    [viewControllers removeLastObject];
    [viewControllers addObject:newVC];
    [[self getRootNavigationController] setViewControllers:viewControllers animated:YES];
}

//获取当前屏幕中present出来的viewcontroller
+ (UIViewController *)getPresentedViewController {
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = appRootVC;
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}

//异或操作，两个异或
+ (Byte) xorByteA:(Byte) a AndByteB:(Byte) b {
    return (Byte) (0xFF & ((0xFF & a) ^ (0xFF & b)));
}

//多个异或
+ (Byte) xorsBytes:(Byte) byte, ...NS_REQUIRES_NIL_TERMINATION {
    if (byte) {
        // 取出第一个参数
        Byte a = byte;
        // 定义一个指向个数可变的参数列表指针；
        va_list args; // 用于存放取出的参数
        Byte b;
        va_start(args, byte); // 遍历全部参数 va_arg返回可变的参数(a_arg的第二个参数是你要返回的参数的类型)
        while ((b = va_arg(args, int))) {
            a = [self xorByteA:a AndByteB:b];
        }
        // 清空参数列表，并置参数指针args无效
        va_end(args);
        return a;
    }
    NSAssert(byte, @"至少要有一个参数");
    return 0x00;
}

//给音频文件加头
+ (NSData *) addHeaderSign:(NSData *) fileData {
    
    long longSampleRate = 8000;
    int channels = 2;
    long byteRate = 16 * 8000 * channels / 8;
    long totalAudioLen = fileData.length;
    long totalDataLen = totalAudioLen + 36;
    
    
    Byte *header = malloc(sizeof(Byte) * 44);
    header[0] = 'R'; // RIFF/WAVE header
    header[1] = 'I';
    header[2] = 'F';
    header[3] = 'F';
    header[4] = (Byte) (totalDataLen & 0xff);
    header[5] = (Byte) ((totalDataLen >> 8) & 0xff);
    header[6] = (Byte) ((totalDataLen >> 16) & 0xff);
    header[7] = (Byte) ((totalDataLen >> 24) & 0xff);
    header[8] = 'W';
    header[9] = 'A';
    header[10] = 'V';
    header[11] = 'E';
    header[12] = 'f'; // 'fmt ' chunk
    header[13] = 'm';
    header[14] = 't';
    header[15] = ' ';
    header[16] = 16; // 4 bytes: size of 'fmt ' chunk
    header[17] = 0;
    header[18] = 0;
    header[19] = 0;
    header[20] = 1; // format = 1
    header[21] = 0;
    header[22] = (Byte) channels;
    header[23] = 0;
    header[24] = (Byte) (longSampleRate & 0xff);
    header[25] = (Byte) ((longSampleRate >> 8) & 0xff);
    header[26] = (Byte) ((longSampleRate >> 16) & 0xff);
    header[27] = (Byte) ((longSampleRate >> 24) & 0xff);
    header[28] = (Byte) (byteRate & 0xff);
    header[29] = (Byte) ((byteRate >> 8) & 0xff);
    header[30] = (Byte) ((byteRate >> 16) & 0xff);
    header[31] = (Byte) ((byteRate >> 24) & 0xff);
    header[32] = (Byte) (2 * 16 / 8); // block align
    header[33] = 0;
    header[34] = 16; // bits per sample
    header[35] = 0;
    header[36] = 'd';
    header[37] = 'a';
    header[38] = 't';
    header[39] = 'a';
    header[40] = (Byte) (totalAudioLen & 0xff);
    header[41] = (Byte) ((totalAudioLen >> 8) & 0xff);
    header[42] = (Byte) ((totalAudioLen >> 16) & 0xff);
    header[43] = (Byte) ((totalAudioLen >> 24) & 0xff);
    
    
    NSData *headerData = [NSData dataWithBytes:header length:44];
    
    NSLog(@"headerData = %@", headerData);
    
    NSMutableData *resultData = [NSMutableData dataWithData:headerData];
    [resultData appendData:fileData];
    
    return resultData;
}
@end
